<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>监听数据对象</title>
</head>

<body>
    <div id="app">
        <input type="text" id="a" v-model='text'> {{text}}
    </div>

    <script>  
        var vm = new Vue({
            el: '#app',
            data: {
                text: 'hello word'
            }
        })

        function Vue(options) {
            this.el = options.el;
            this.data = options.data;
            observe(this.data,this)
            var nodes = document.querySelector(this.el);
            var dom = node2fragment(nodes, this.data);
            nodes.appendChild(dom);
        }
        Vue.prototype = {

        }
        //遍历编译节点插入碎片
        function node2fragment(node, obj) {
            var child;
            var fragment = document.createDocumentFragment();
            while (child = node.firstChild) {
                compile(child, obj)
                fragment.appendChild(child)

            }
            return fragment;
        }

        //编译节点
        function compile(node, obj) {
            var type = node.nodeType;
            //1为元素节点 3为文本节点
            if (type == 1) {
                //去属性集合
                var attrs = node.attributes;
                for (let index = 0; index < attrs.length; index++) {
                    if (attrs[index].nodeName == "v-model") {
                        var name = attrs[index].nodeValue;
                        node.value = obj[name];
                        //当编译时，存在需要双向绑定的元素时，添加观察者对象
                        new Watcher();
                    }
                }
            } else if (type == 3) {
                //匹配获取name
                var reg = /\{\{(.*)\}\}/;
                if (reg.test(node.nodeValue)) {
                    var name = RegExp.$1.trim();
                    node.nodeValue = obj[name];
                    //当编译时，存在需要双向绑定的元素时，添加观察者对象
                    new Watcher();
                }
            }
        }

        //监听
        function observe(obj,vm){
            Object.keys(obj).forEach((key)=>{
                Object.defineProperty(vm,key,{
                    set:(newValue)=>{
                        if(obj[key]==newValue){
                            return;
                        }
                        obj[key]=newValue;
                        //被改变时，发布者去通知所有观察者whatcher
                        Dep.notify();
                    },
                    get:()=>{
                        return obj[key];
                    }
                })
            })
        }
    </script>
</body>

</html>